import { createWebHashHistory, createRouter } from "vue-router";
import index from '../view/index.vue'
import UserManagement from '../view/UserManagement.vue'
import AdminManagement from '../view/AdminManagement.vue'
import AddressManagement from '../view/AddressManagement.vue'
import TypeManagement from '../view/TypeManagement.vue'
import GoodsManagement from '../view/GoodsManagement.vue'
import UserGoodsPage from '../view/UserGoodsPage.vue'
import SeckillActivityManagement from '../view/SeckillActivityManagement.vue'
import SeckillGoodsManagement from '../view/SeckillGoodsManagement.vue'
import Login from '../view/Login.vue'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path:'/login',
        name:'Login',
        component:Login,
    },
    {
        path: '/goods',
        name: 'UserGoodsPage',
        component: UserGoodsPage
    },
    {
        path: '/index',
        name: 'index',
        component: index,
        children: [
            {
                path:'AdminManagement',
                component:AdminManagement
            },
            {
                path:'UserManagement',
                component:UserManagement
            },
            {
                path:'AddressManagement',
                component:AddressManagement
            },
            {
                path:'TypeManagement',
                component:TypeManagement
            },
            {
                path:'GoodsManagement',
                component:GoodsManagement
            },
            {
                 path: 'seckill-activity-management',
                 name: 'SeckillActivityManagement',
                 component: SeckillActivityManagement
             },
            {
                 path: 'seckill-goods-management',
                 name: 'SeckillGoodsManagement',
                 component: SeckillGoodsManagement
             },
        ]
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const userType = localStorage.getItem('userType');
  
  // 如果访问登录页
  if (to.path === '/login') {
    // 如果已经登录，直接跳转到主页
    if (token) {
      next('/index');
    } else {
      next();
    }
    return;
  }
  
  // 如果访问其他页面但没有登录，跳转到登录页
  if (!token) {
    next('/login');
    return;
  }
  
  // 已登录用户正常访问
  next();
});

export default router;
